<?php
namespace app\index\controller;
use think\App;
use think\Controller ;
use Db;
use EasyWeChat\Factory;


class Base extends Controller
{
    public $uid = 0;
    public $userInfo = [];
    public function __construct(App $app = null)
    {
        parent::__construct($app);

        $token = cookie('ticket');
        $url = request()->url();


        if($code = input('invite_code')){

            cookie('invite_code',$code);
        }


        #微信浏览器默认使用微信登录
        $is_wexin = isWeixin();

        if($is_wexin){

            $config = [
                'app_id' => config('wechat.AppId'),
                'secret' => config('wechat.AppSecret'),

                // 指定 API 调用返回结果的类型：array(default)/collection/object/raw/自定义类名
                'response_type' => 'array',
                'oauth' => [
                    'scopes'   => ['snsapi_userinfo'],
                    'callback' => '/index/index/wxLogin/?invite_code='.$code,
                ],
            ];

            $app = Factory::officialAccount($config);


            if(!$token){
                cookie('target_url',$url);

                $this->ajaxError();
                //没有登录凭证
                $app->oauth->redirect()->send();

            }else{

                //登录凭证已过期
//                $res =  DB::name('user')->field('phone,level_validity,id,pid,ppid,role,earnings,total_earnings,money,level,invite_code,nickname,wx_openid')->where('login_token',$token)->find();
                $res =  DB::name('user')->where('login_token',$token)->find();
                if(!$res){
                    cookie('target_url',$url);

                    $this->ajaxError();

                    $app->oauth->redirect()->send();
                }

            }
//            $this->error('请先登录');
        }else{

            #手机号登录

            if(!$token){
                cookie('target_url',$url);

                //没有登录凭证
                $this->ajaxError();

                $this->redirect('/index/index/login');


            }else{

                //登录凭证已过期
//                $res =  DB::name('user')->field('phone,level_validity,id,pid,ppid,earnings,total_earnings,money,level,nickname,invite_code,wx_openid')->where('login_token',$token)->find();
                $res =  DB::name('user')->where('login_token',$token)->find();
                if(!$res){
                    cookie('target_url',$url);
                    $this->ajaxError();

                    $this->redirect('/index/index/login');

                }

            }

        }


        $this->uid = $res['id'];
        $this->userInfo = $res;


    }


    public function ajaxError(){

        if(request()->isAjax()){

            exit(json_encode(['code'=>0,'msg'=>'请刷新页面登录']));
        }
    }

}
